import * as signalR from '@microsoft/signalr'
import { getToken } from '@/utils/auth'

class SignalRService {
  constructor() {
    this.connection = null
    this.hubUrl = process.env.VUE_APP_BASE_API + '/chatHub'
    this.messageHandlers = new Map()
    this.typingHandlers = new Map()
    this.userJoinHandlers = new Map()
    this.userLeaveHandlers = new Map()
  }

  async startConnection() {
    try {
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl(this.hubUrl, {
          accessTokenFactory: () => getToken()
        })
        .withAutomaticReconnect()
        .build()

      // 注册消息处理器
      this.connection.on('ReceiveMessage', (message) => {
        this.messageHandlers.forEach(handler => handler(message))
      })

      this.connection.on('UserTyping', (data) => {
        this.typingHandlers.forEach(handler => handler(data))
      })

      this.connection.on('UserJoined', (data) => {
        this.userJoinHandlers.forEach(handler => handler(data))
      })

      this.connection.on('UserLeft', (data) => {
        this.userLeaveHandlers.forEach(handler => handler(data))
      })

      await this.connection.start()
      console.log('SignalR Connected')
    } catch (err) {
      console.error('SignalR Connection Error: ', err)
    }
  }

  async stopConnection() {
    try {
      await this.connection.stop()
      console.log('SignalR Disconnected')
    } catch (err) {
      console.error('SignalR Disconnection Error: ', err)
    }
  }

  // 加入聊天组
  async joinGroup(groupId) {
    try {
      await this.connection.invoke('JoinGroup', groupId)
    } catch (err) {
      console.error('Join Group Error: ', err)
    }
  }

  // 离开聊天组
  async leaveGroup(groupId) {
    try {
      await this.connection.invoke('LeaveGroup', groupId)
    } catch (err) {
      console.error('Leave Group Error: ', err)
    }
  }

  // 发送消息
  async sendMessage(groupId, message) {
    try {
      await this.connection.invoke('SendMessage', groupId, message)
    } catch (err) {
      console.error('Send Message Error: ', err)
    }
  }

  // 发送正在输入状态
  async sendTypingStatus(groupId, isTyping) {
    try {
      await this.connection.invoke('SendTypingStatus', groupId, isTyping)
    } catch (err) {
      console.error('Send Typing Status Error: ', err)
    }
  }

  // 注册消息处理器
  onMessage(handler) {
    const id = Date.now()
    this.messageHandlers.set(id, handler)
    return () => this.messageHandlers.delete(id)
  }

  // 注册输入状态处理器
  onTyping(handler) {
    const id = Date.now()
    this.typingHandlers.set(id, handler)
    return () => this.typingHandlers.delete(id)
  }

  // 注册用户加入处理器
  onUserJoin(handler) {
    const id = Date.now()
    this.userJoinHandlers.set(id, handler)
    return () => this.userJoinHandlers.delete(id)
  }

  // 注册用户离开处理器
  onUserLeave(handler) {
    const id = Date.now()
    this.userLeaveHandlers.set(id, handler)
    return () => this.userLeaveHandlers.delete(id)
  }
}

export default new SignalRService() 